import { Global } from './../../common/global';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { TimeoutError } from 'rxjs/Rx';
import { NativeProvider } from '../native/native';
import { App } from 'ionic-angular';

/*
  Generated class for the HttpProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class HttpProvider {
  constructor(public http: HttpClient,private native: NativeProvider, private app: App) {
    console.log('Hello HttpProvider Provider');
  }
  public postNoloading(url, queryParams?, body?) {
      return this.post(false,url, queryParams, body);
  }
  public postLoading(url, queryParams?, body?) {
      return this.post(true,url, queryParams, body);
  }
  public post(showloading: boolean, url, queryParams?, body?) {
    url = Global.base_url + url;
    return Observable.create(observer => {
      if (showloading) {
        this.native.showLoading();
      }
      body = JSON.stringify(body);
      this.http.post(url, body, this.getJsonRequestOptions(queryParams)).timeout(5000).subscribe(
        res => {
          if (showloading) {
            this.native.hideLoading();
          }
          if (!res["_success"]) {
            if(res["code"] == "401"){
              this.native.showToast(res["_message"]);
              this.app.getRootNav().setRoot("LoginPage");
              observer.error(res["_message"]);
            }else{
              this.native.alert(res["_message"]);
              observer.error(res["_message"]);
            }
          } else {
            observer.next(res["result"]);
          }
        },
        err => {
          if (showloading) {
            this.native.hideLoading();
          }
          observer.error(this.requestFailedHandle(err));

        }
      );
    })
  }
  private requestFailedHandle(err: Response) {
    const status = err.status;
    let msg = '请求发生异常，请联系管理员';
    if (!this.native.isConnecting()) {
      this.native.alert('请连接网络');
    } else if (err instanceof TimeoutError) {
      this.native.alert('请求超时,请稍后再试!');
    } else {
      if (status === 0) {
        msg = '请求失败，可能后台服务未启用';
      } else if (status === 404) {
        msg = '请求失败，未找到请求地址';
      } else if (status === 500) {
        msg = '请求失败，服务器出错，请稍后再试';
      }
      this.native.alert(msg);
    }
    return err;
  }

  private getJsonRequestOptions(queryParams) {
    let token = localStorage.getItem(Global.token);
    if(token == null){
      token ="";
    }
    let headers = {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      "Authorization": token,
      "Mobile":"true"
    };
    let options = { headers: headers, params: queryParams };
    return options;
  }
}
